package com.example.service;

import com.example.dto.LoginRequest;
import com.example.dto.LoginResponse;
import com.example.dto.RegisterRequest;
import com.example.mapper.DbConnectionMapper;
import com.example.mapper.SqlExecutionMapper;
import com.example.mapper.SqlHistoryMapper;
import com.example.mapper.UserMapper;
import com.example.model.User;
import com.example.model.UserRole;
import com.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {
    private static final Logger log = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private SqlHistoryMapper sqlHistoryMapper;
    
    @Autowired
    private SqlExecutionMapper sqlExecutionMapper;
    
    @Autowired
    private DbConnectionMapper dbConnectionMapper;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public void register(RegisterRequest request) {
        // 检查用户名是否已存在
        User existingUser = userMapper.findByUsername(request.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在，请更换其他用户名");
        }
        
        // 密码长度验证
        if (request.getPassword().length() < 6) {
            throw new RuntimeException("密码长度不能少于6个字符");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setRole(UserRole.ROLE_USER.name()); // 默认为普通用户
        user.setCreatedAt(LocalDateTime.now());
        
        userMapper.insert(user);
    }

    public Map<String, Object> login(String username, String password) {
        // 验证用户名和密码
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在，请先注册");
        }
        
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码错误，请重新输入");
        }
        
        // 生成 token
        String token = jwtUtil.generateToken(user.getId());
        
        // 返回用户信息和token
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("username", user.getUsername());
        userInfo.put("role", user.getRole()); // 添加角色信息
        result.put("userInfo", userInfo);
        
        return result;
    }

    public void logout(Long userId) {
        // 记录用户登出日志
        log.info("User {} logged out", userId);
    }
    
    // 获取所有用户
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }
    
    /**
     * 分页获取所有用户
     * @param page 页码（从1开始）
     * @param pageSize 每页记录数
     * @return 分页后的用户列表
     */
    public List<User> getPagedUsers(int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        return userMapper.findAllPaged(offset, pageSize);
    }
    
    /**
     * 获取用户总数
     */
    public int getUserCount() {
        return userMapper.count();
    }
    
    // 获取指定角色的用户
    public List<User> getUsersByRole(String role) {
        return userMapper.findByRole(role);
    }
    
    /**
     * 分页获取指定角色的用户
     * @param role 角色
     * @param page 页码（从1开始）
     * @param pageSize 每页记录数
     * @return 分页后的用户列表
     */
    public List<User> getPagedUsersByRole(String role, int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        return userMapper.findByRolePaged(role, offset, pageSize);
    }
    
    /**
     * 获取指定角色的用户总数
     */
    public int getUserCountByRole(String role) {
        return userMapper.countByRole(role);
    }
    
    // 更新用户角色
    public void updateUserRole(Long userId, String role) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证角色是否有效
        try {
            UserRole.valueOf(role);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("无效的角色类型");
        }
        
        userMapper.updateRole(userId, role);
    }
    
    // 删除用户
    @Transactional
    public void deleteUser(Long userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 防止删除管理员
        if (UserRole.ROLE_ADMIN.name().equals(user.getRole())) {
            throw new RuntimeException("不能删除管理员账户");
        }
        
        // 先删除用户相关数据，再删除用户本身
        
        // 1. 删除用户的SQL历史记录
        sqlHistoryMapper.deleteByUserId(userId);
        
        // 2. 删除用户的SQL执行记录
        sqlExecutionMapper.deleteByUserId(userId);
        
        // 3. 删除用户的数据库连接
        dbConnectionMapper.deleteByUserId(userId);
        
        // 4. 最后删除用户
        userMapper.deleteById(userId);
        
        log.info("用户删除成功，ID: {}, 用户名: {}", userId, user.getUsername());
    }

    // 通过ID获取用户
    public User getUserById(Long userId) {
        return userMapper.findById(userId);
    }
} 